//
//  AddBankNumViewController.m
//  1243
//
//  Created by 杨森 on 16/5/11.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "AddBankNumViewController.h"
#import "CardNameTableViewCell.h"
#import "CardNumberTableViewCell.h"
#import "ChoseBankViewController.h"
#import "CardTypeTableViewController.h"
#import "NetWorkTools.h"
#import "choseBankTableViewController.h"
@interface AddBankNumViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIAlertViewDelegate>
{
    NSString *type;
    NSString *number;
    NSString *BankName;
    NSString *temp;
    NSString *cardType;
}

@property (nonatomic, strong)UITextField *cardIdFeild;
@property (nonatomic,strong)UITableView *addTableView;
@end

@implementation AddBankNumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCard:) name:@"choseCard" object:nil];
    self.title = @"添加银行卡";
    
    self.view.backgroundColor = BACKGROUND_COLOR;
    
    [self addViews];
}
- (void)changeCard:(NSNotification *)noti {
    
    cardType = noti.userInfo[@"name"];
   
    [self.addTableView reloadData];
}
- (void)addViews
{
    self.addTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WEITH, HEIGHT) style:UITableViewStyleGrouped];
    self.addTableView .delegate = self;
    self.addTableView .dataSource = self;
    [self.view addSubview:self.addTableView ];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated
     ];
    
}

#pragma mark >>>>>>>>dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        static NSString *identifier= @"CardNameTableViewCell";
        
        CardNameTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell==nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CardNameTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        NSDictionary *dict = [ReadLoginData readLoginData];
        NSString *RealName = [dict objectForKey:@"RealName"];
        cell.cardNameLabel.text = RealName;
        return cell;
        
    }else if (indexPath.row ==1){
        
        static NSString *identifier= @"CardNameTableViewCell";
        
        CardNameTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell==nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CardNameTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.cardNameLabel.text = cardType;
       cell.FristLabel.text = @"卡类型";
        return cell;
        
    }else{
        
        static NSString *identifier= @"CardNumberTableViewCell";
        
        CardNumberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell==nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CardNumberTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.cardNumberTextFiled.delegate = self;
        cell.cardNumberTextFiled.tag = 13454;
        self.cardIdFeild = cell.cardNumberTextFiled;

        return cell;
        
    }
    
}
- (void) textFieldChange:(NSNotification *)notification:(UITextField *)TextField{
    
    
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
  //  choseBankTableViewController *typeVc = [[choseBankTableViewController alloc] init];
   // [self.navigationController pushViewController:typeVc animated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"3%lu",textField.text.length);
    
    if (textField.text.length >= 16) {
        NSString *httpUrl = @"http://apis.baidu.com/datatiny/cardinfo/cardinfo";
        NSString *httpArg = [NSString stringWithFormat:@"cardnum=%@",textField.text];
        [self request: httpUrl withHttpArg: httpArg];
    }
    
    if (textField.tag == 13453) {
        
        NSString *newString = nil;
        newString = [textField.text stringByAppendingString:string];
        type = newString;
        return YES;
    }else{
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength >= 20) {
            
            
            return NO;
        }
        
        NSString *newStringA = nil;
        newStringA = [textField.text stringByAppendingString:string];
        number = newStringA;
        return YES;
    }
    
    
   
}

- (void)textFieldDidChange:(UITextField *)textField
{
    NSLog(@"2%@",textField.text);
    if (textField == self.cardIdFeild) {
        if (textField.text.length >=20) {
            textField.text = [textField.text substringToIndex:20];
        }
    }
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"1%@",textField.text);
    if (textField.tag ==13454 ) {
        NSString *httpUrl = @"http://apis.baidu.com/datatiny/cardinfo/cardinfo";
        NSString *httpArg = [NSString stringWithFormat:@"cardnum=%@",textField.text];
        [self request: httpUrl withHttpArg: httpArg];
    }
    
}
// 6217850500020351270

#pragma mark --- 请求银行数据
-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"7f6d292da39ee1a302ac72190760d651" forHTTPHeaderField: @"apikey"];
    
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){                               
                           
                               
                               NSError *err;
                               
                               NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                                   options:NSJSONReadingMutableContainers
                                                    
                                                                                     error:&err];
                               NSLog(@"dicdic%@",dic);
                               BankName   =  dic[@"data"][@"bankname"];
                               NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
                               [self.addTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

                           }];
    
    
}

#pragma mark >>>>>>>>>delegate
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}

 - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] init];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTintColor:[UIColor whiteColor]];
    [button setTitle:@"添加成功" forState:UIControlStateNormal];
//    [button setBackgroundColor:NAVBAR_COLOR];
    [button setBackgroundColor:[UIColor orangeColor]];
    button.frame = CGRectMake(10, 10, WEITH-20, 40);
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    [footView addSubview:button];
    [button addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    return footView;
}

- (void)addButtonClick
{
//    NSLog(@"添加成功");
    
    if (cardType.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入银行卡类型" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        
        [alert show];
    }else{
        if (number.length >= 12 &&number.length <=25 ) {
            [self data];
        }else{
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您输入的银行卡不符合要求" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            
            [alert show];
            
        }
        
    }
    
    
   
}
- (void)data{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
//  {"MenthodName":"BANKINFOADD","MenthodParms":"{\"Number\":0,\"U_Number\":6517,\"UserName\":\"test\",\"Email\":null,\"RealName\":\"testBank\",\"Sex\":null,\"Birthday\":\"1753-02-02T12:00:00\",\"QQ\":null,\"Mobile\":null,\"ID_Card\":\"330528198990907682\",\"Phone\":null,\"Company\":null,\"HeadImg\"     :null,\"Adrress\":null,\"Zipcode\":null,\"Province\":\"浙江省\",\"City\":\"杭州市\"      ,\"Country\":null,\"CreateIp\":null,\"CreateTime\":\"0001-01-01T00:00:00\",\"IsEmail\":0,\"IsMobile\":0,\"Bank_Info\":\"招商银行\",\"Bank_Code\":\"994810447788\",\"WW\":\"招商银行杭州分行杭大营业处\",\"Remark\":null}","Sign":"EA31387184B0ED4279566127D74E979912A59DBD"}
    
    NSString *UNumber = [dict objectForKey:@"Number"];
     NSString *userName = [dict objectForKey:@"UserName"];
    NSString *RealName = [dict objectForKey:@"RealName"];
    
    NSDictionary *params = @{
                             @"Number":@"0",
                              @"U_Number":UNumber,
                             @"UserName":userName,
                             @"Email":@"",
                             @"RealName":RealName,
                             @"Sex":@"",
                             @"Birthday":@"1753-02-02T12:00:00",
                             @"QQ":@"",
                              @"Mobile":@"",
                             @"ID_Card":@"330528198990907682",
                             @"Phone":@"",
                             @"Company":@"",
                             @"HeadImg":@"",
                             @"Adrress":@"",
                             @"Zipcode":@"",
                             @"Province":@"浙江省",
                             @"City":@"杭州市",
                             @"Country":@"",
                             @"CreateIp":@"",
                            @"CreateTime":@"0001-01-01T00:00:00",
                            @"IsEmail":@"0",
                             @"IsMobile":@"0",
                             @"WW":@"招商银行杭州分行杭大营业处",
                             @"Bank_Info":cardType,
                             @"Bank_Code":number,

                             };
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"BANKINFOADD" completeBlock:^(id object) {
              NSLog(@"Bank_Info%@",object[@"Message"]);
     
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:object[@"Message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 99999;
     
        [alert show];
    }];
    //    [self.tableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 99999) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 1) {
        choseBankTableViewController *typeVc = [[choseBankTableViewController alloc] init];
        [self.navigationController pushViewController:typeVc animated:YES];
    }
}

//tabBar 隐藏
- (void)pushForm:(UINavigationController *)pushForm pushToAndHidden:(UIViewController *)pushToVC
{
    [pushToVC setHidesBottomBarWhenPushed:YES];
    [pushForm pushViewController:pushToVC animated:YES];
    
}


@end
